Router.route("/wechat/oauth", function() {
    var request = this.request;
    var code = request.query.code,
        state = request.query.state;

    var token = getAccessToken(code);

    var userinfo =  getUserInfo(token.access_token , token.openid);
    // console.log(token);
    // console.log(userinfo);
   
    userinfo = _.extend(token , userinfo);

    if(!Accounts.findUserByUsername(userinfo.nickname)){
      Accounts.createUser({
        username : userinfo.nickname,
        email : userinfo.openid + "@qq.com",
        password: "123456",
        profile :userinfo,
      });
    }

    var redirectUrl = __meteor_runtime_config__.ROOT_URL + '?username='+ userinfo.openid +'&state=' + state;
    console.log(redirectUrl);
    this.response.writeHead(302, {
      'Location': redirectUrl
    });

    this.response.end();
   
}, {
    where: "server"
});

var stateFromQuery = function (query) {
  if(query === '')return query;
  var string;
  try {
    string = new Buffer(query.state, 'base64').toString('binary');
  } catch (e) {
    console.log('Unable to base64 decode state from OAuth query: ' + query.state);
    throw e;
  }
  return string;
  // try {
  //   return JSON.parse(string);
  // } catch (e) {
  //   Log.warn('Unable to parse state from OAuth query: ' + string);
  //   throw e;
  // }
};

var getAccessToken = function(code) {
    var config = ServiceConfiguration.configurations.findOne({
        service: 'wechat'
    });
    if (!config) throw new ServiceConfiguration.ConfigError();

    var loginUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token' +
      '?appid=' + config.appId +
      '&secret=' + config.secret +
      '&code=' + code +
      '&grant_type=authorization_code';

    return http(loginUrl);
 
}

var getUserInfo = function(accessToken, openId) {

      var loginUrl = 'https://api.weixin.qq.com/sns/userinfo' +
      '?access_token=' + accessToken +
      '&openid=' + openId +
      '&lang=zh_CN';

      return http(loginUrl);
  }


var http = function(url) {
    var response;
    try {
        response = HTTP.get(url);
        if (response.error) // if the http response was an error
            throw response.error;
        if (typeof response.content === "string") response.content = JSON.parse(response.content);
        if (response.content.errcode) throw response.content.errmsg;
    } catch (err) {
        throw _.extend(new Error("Failed to complete OAuth handshake with Wechat. " + err));
    }
   
    return response.content;
};